package com.horse.three60;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.fb.android.FacebookShareManager;
import com.horse.share.twitter.TwitterShareManager;
import com.horse.utils.Constants;
import com.horse.utils.Downloader;
import com.horse.utils.ImageName;
import com.horse.utils.NoRepeatRandom;
import com.horse.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class LearningQuizeActivity extends Activity implements OnClickListener {

	private TextView timerView;
	private TextView scoreView;
	private ImageView pauseView;
	private ImageView imageView;

	private Button firstButton;
	private Button secondButton;
	private Button thirdButton;
	private Button fourthButton;
	private Button exitButton;
	private Button resumeButton;

	private boolean isTimer;
	private String jsonString;

	private int targetPosition[];

	private int unTargetPosition[] = new int[3];

	private NoRepeatRandom nrr;

	private List<int[]> positionList;
	private int randomValue;

	private int currentIndex = -1;
	private int score = 0;

	private TextView quesTextView;

	private boolean isClick;
	private boolean isExit;
	private boolean isNextQuestion = true;

	private TextView alertView;
	private TextView congratulationView;
	private TextView miliView;

	private String fileName;
	private String compareText;

	private boolean isNextLevel;
	private int level;

	private long remainingTime = 0;
	private int bonusScore = 0;
	private CountDownTimer timer;

	private long pauseBefore;
	private long pauseAfter;
	private long pauseTime = 0;
	private boolean isPause;

	private File files[];

	private boolean isHoofContains;
	private int countCorrectAnswer = 0;

	private long waitForNext = 0;

	private ImplementQuize iquize;
	private int quizeIndex = -1;
	private int numOfQuestion;

	private JSONArray ja;
	private JSONObject jo;

	private TextView tView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_quize);

			congratulationView = (TextView) findViewById(R.id.congratulationView);
			alertView = (TextView) findViewById(R.id.alertView);
			imageView = (ImageView) findViewById(R.id.imageView);
			timerView = (TextView) findViewById(R.id.timerView);
			scoreView = (TextView) findViewById(R.id.scoreView);
			quesTextView = (TextView) findViewById(R.id.questionNumberView);
			tView = (TextView) findViewById(R.id.tView);

			pauseView = (ImageView) findViewById(R.id.pauseView);
			pauseView.setOnClickListener(this);

			firstButton = (Button) findViewById(R.id.firstButton);
			firstButton.setOnClickListener(this);

			secondButton = (Button) findViewById(R.id.secondButton);
			secondButton.setOnClickListener(this);

			thirdButton = (Button) findViewById(R.id.thirdButton);
			thirdButton.setOnClickListener(this);

			fourthButton = (Button) findViewById(R.id.fourthButton);
			fourthButton.setOnClickListener(this);

			exitButton = (Button) findViewById(R.id.exitButton);
			exitButton.setOnClickListener(this);

			resumeButton = (Button) findViewById(R.id.resumeButton);
			resumeButton.setOnClickListener(this);

			positionList = new ArrayList<int[]>();

			isTimer = getIntent()
					.getBooleanExtra(Constants.KEY_IS_TIMER, false);
			if (!isTimer) {
				timerView.setVisibility(View.GONE);
				findViewById(R.id.tView).setVisibility(View.GONE);
			}
			level = getIntent().getIntExtra(Constants.KEY_LEVEL, 0);
			jsonString = getJsonString(level);

			// implementQuize();
			iquize = new ImplementQuize(quizeIndex, Constants.WAITING_TIME);
			iquize.execute("" + quizeIndex);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onClick(View v) {
		String text = thirdButton.getText().toString();
		int viewId = v.getId();
		if ((viewId == R.id.firstButton) || (viewId == R.id.secondButton)
				|| (viewId == R.id.thirdButton)
				|| (viewId == R.id.fourthButton)) {
			// firstButton.setEnabled(false);
			// secondButton.setEnabled(false);
			// thirdButton.setEnabled(false);
			// fourthButton.setEnabled(false);
			if (isTimer) {
				timer.cancel();
				// waitForNext = Math.min(remainingTime, 1000);
			}

		}
		switch (viewId) {
		case R.id.firstButton:
			if (!text.equals("")) {
				if (isClick) {
					compareText = firstButton.getText().toString();
					buttonClicked(0);
					isClick = false;
					isNextQuestion = true;
				}
			} else {
				isExit = true;
				imageView.setAlpha(0xFF);
				Intent backIntent = new Intent(LearningQuizeActivity.this,
						LearningBeforeActivity.class);
				backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(backIntent);
			}
			break;
		case R.id.secondButton:
			if (!text.equals("")) {
				if (isClick) {
					compareText = secondButton.getText().toString();
					buttonClicked(1);
					isClick = false;
					isNextQuestion = true;

				}
			} else {
				currentIndex = -1;
				isExit = false;
				score = 0;
				scoreView.setText("" + score);
				imageView.setAlpha(0xFF);
				alertView.setVisibility(View.GONE);
				quesTextView.setVisibility(View.VISIBLE);
				if (!isNextLevel) {
					Intent intent = new Intent(LearningQuizeActivity.this,
							LearningQuizeActivity.class);
					intent.putExtra(Constants.KEY_IS_TIMER, isTimer);
					intent.putExtra(Constants.KEY_LEVEL, level);
					startActivity(intent);
					// implementQuize();
				} else {
					if ((level < 2) || (level == 19)) {
						++level;
						Intent intent = new Intent(LearningQuizeActivity.this,
								LearningQuizeActivity.class);
						Log.i("DREG", "is Normal=" + isTimer);
						intent.putExtra(Constants.KEY_IS_TIMER, isTimer);
						intent.putExtra(Constants.KEY_LEVEL, level);
						startActivity(intent);
					} else {
						++level;
						try {
							files = Downloader
									.getFileList(getImageDirectory(level));
							if (files != null) {
								Intent i = new Intent(
										LearningQuizeActivity.this,
										LearningQuizeActivity.class);
								i.putExtra(Constants.KEY_IS_TIMER, isTimer);
								i.putExtra(Constants.KEY_LEVEL, level);
								i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(i);
							} else {
								Intent backIntent = new Intent(
										LearningQuizeActivity.this,
										LearningBeforeActivity.class);
								backIntent.putExtra(Constants.KEY_NEXT_LEVEL,
										level);
								backIntent
										.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(backIntent);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
			break;
		case R.id.thirdButton:
			if (!text.equals("")) {
				if (isClick) {
					compareText = thirdButton.getText().toString();
					buttonClicked(2);
					isNextQuestion = true;
					isClick = false;
				}
			} else {
				faceBookSharing("I have just scored " + score + " in Horse 360");
			}
			break;
		case R.id.fourthButton:
			if (!text.equals("")) {
				if (isClick) {
					compareText = fourthButton.getText().toString();
					buttonClicked(3);
					isNextQuestion = true;
					isClick = false;

				}
			} else {
				shareInTwitter();
			}
			break;
		case R.id.exitButton:
			isExit = true;
			imageView.setAlpha(0xFF);
			alertView.setVisibility(View.GONE);
			Intent backIntent = new Intent(LearningQuizeActivity.this,
					LearningBeforeActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			break;
		case R.id.resumeButton:
			isPause = false;
			// isNextQuestion = true;
			if (isTimer) {
				Log.i("DREG", "Remaining time =" + remainingTime);
				iquize = new ImplementQuize(quizeIndex, remainingTime);
				iquize.execute();
			}

			pauseAfter = System.currentTimeMillis();
			imageView.setAlpha(0xFF);
			imageView.setVisibility(View.VISIBLE);
			firstButton.setVisibility(View.VISIBLE);
			secondButton.setVisibility(View.VISIBLE);
			thirdButton.setVisibility(View.VISIBLE);
			fourthButton.setVisibility(View.VISIBLE);
			exitButton.setVisibility(View.GONE);
			resumeButton.setVisibility(View.GONE);
			break;
		case R.id.pauseView:
			if (isTimer) {
				timer.cancel();
				iquize.cancel(true);
				isPause = true;
			}
			pauseBefore = System.currentTimeMillis();
			pauseTime = (pauseAfter - pauseBefore) % 1000;
			imageView.setAlpha(0x7F);
			alertView.setVisibility(View.GONE);
			firstButton.setVisibility(View.GONE);
			secondButton.setVisibility(View.GONE);
			thirdButton.setVisibility(View.GONE);
			fourthButton.setVisibility(View.GONE);
			exitButton.setVisibility(View.VISIBLE);
			resumeButton.setVisibility(View.VISIBLE);
			break;

		default:
			break;

		}

	}

	private void buttonClicked(int position) {
		// isNextQuestion=true;

		if (compareText.contains("vertabrae")) {
			compareText = compareText.replace("vertabrae", "vertebrae");
		}
		if (isHoofContains) {
			compareText = compareText + "_(HOOFSIDE)";
		}

		pauseView.setEnabled(false);
		// if (fileName.equalsIgnoreCase(compareText)) {
		if (position == randomValue) {
			++countCorrectAnswer;
			score += 10 + bonusScore;
			scoreView.setText("" + score);
			if (isTimer) {
				quesTextView.setText(bonusScore + " Bonus points");
			}
			if (!(thirdButton.getText().toString().equals(""))) {
				Utils.play(this, R.raw.sound_correct);
			}
			switch (position) {
			case 0:
				firstButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// firstButton.setTextColor(Color.GREEN);
				break;
			case 1:
				secondButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// secondButton.setTextColor(Color.GREEN);
				break;
			case 2:
				thirdButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// thirdButton.setTextColor(Color.GREEN);
				break;
			case 3:
				fourthButton
						.setBackgroundResource(R.drawable.quiz_answer_correct);
				// fourthButton.setTextColor(Color.GREEN);
				break;
			default:
				break;
			}
		} else {
			if (!(thirdButton.getText().toString().equals(""))) {
				Utils.play(this, R.raw.sound_incorrect);
				Utils.vibratePhone(LearningQuizeActivity.this);
			}
			switch (position) {
			case 0:
				firstButton.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// firstButton.setTextColor(Color.RED);
				break;
			case 1:
				secondButton
						.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// secondButton.setTextColor(Color.RED);
				break;
			case 2:
				thirdButton.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// thirdButton.setTextColor(Color.RED);
				break;
			case 3:
				fourthButton
						.setBackgroundResource(R.drawable.quiz_answer_wrong);
				// fourthButton.setTextColor(Color.RED);
				break;
			default:
				break;
			}

			switch (randomValue) {
			case 0:
				// firstButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				firstButton.setTextColor(Color.GREEN);
				break;
			case 1:
				// secondButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				secondButton.setTextColor(Color.GREEN);
				break;
			case 2:
				// thirdButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				thirdButton.setTextColor(Color.GREEN);
				break;
			case 3:
				// fourthButton.setBackgroundResource(R.drawable.quiz_answer_correct);
				fourthButton.setTextColor(Color.GREEN);
				break;
			default:
				break;
			}
		}
		if (isTimer) {
			try {
				new AsyncTask<String, String, String>() {
					@Override
					protected void onPreExecute() {
						try {
							iquize.cancel(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					protected String doInBackground(String... arg0) {
						try {
							Log.i("DREG", "Quize Index =" + quizeIndex);
							if (quizeIndex < (numOfQuestion - 2)) {
								Thread.sleep(Constants.WAITING_FOR_NEXT);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(String unused) {
						isClick = false;
						if (quizeIndex < (numOfQuestion - 1)) {
							iquize = new ImplementQuize(++quizeIndex,
									Constants.WAITING_TIME);
						}
						iquize.execute();
					}
				}.execute();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	class ImplementQuize extends AsyncTask<String, String, String> {
		private int currentIndex;
		private long waitingTime;
		private String option1;
		private String option2;
		private String option3;
		private String option4;
		private String firstText;
		private String secondText;
		private String thirdText;
		private String fourthText;

		public ImplementQuize(int currentIndex, long waitingTime) {
			super();
			this.currentIndex = currentIndex;
			this.waitingTime = waitingTime;
		}

		@Override
		protected void onPreExecute() {

		}

		protected void onProgressUpdate(String... arg0) {
			try {
				firstButton.setVisibility(View.VISIBLE);
				secondButton.setVisibility(View.VISIBLE);
				thirdButton.setVisibility(View.VISIBLE);
				fourthButton.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.VISIBLE);
				quizeIndex = currentIndex;
				currentIndex++;
				isClick = true;
				isHoofContains = false;

				// Log.i("DREG", "Current Index=" + currentIndex);
				Log.i("DREG", "Random value = " + randomValue);
				firstButton.setBackgroundResource(R.drawable.quize_button);
				secondButton.setBackgroundResource(R.drawable.quize_button);
				thirdButton.setBackgroundResource(R.drawable.quize_button);
				fourthButton.setBackgroundResource(R.drawable.quize_button);

				firstButton.setTextColor(Color.WHITE);
				secondButton.setTextColor(Color.WHITE);
				thirdButton.setTextColor(Color.WHITE);
				fourthButton.setTextColor(Color.WHITE);

				firstButton.setEnabled(true);
				secondButton.setEnabled(true);
				thirdButton.setEnabled(true);
				fourthButton.setEnabled(true);
				pauseView.setEnabled(true);
				
				if (isTimer) {
					showTimer(waitingTime);
				}

//				if (currentIndex < (ja.length())) {
//					waitingTime = 10000;
//				} else {
//					waitingTime = 500;
//				}
				if (currentIndex < ja.length()) {
					

					quesTextView.setText("Question " + (currentIndex + 1));

					fileName = ja.getJSONObject(
							positionList.get(currentIndex)[0]).getString(
							"-part");

					firstText = ja.getJSONObject(
							positionList.get(currentIndex)[0]).getString(
							"-part");

					secondText = ja.getJSONObject(
							positionList.get(currentIndex)[1]).getString(
							"-part");
					thirdText = ja.getJSONObject(
							positionList.get(currentIndex)[2]).getString(
							"-part");
					fourthText = ja.getJSONObject(
							positionList.get(currentIndex)[3]).getString(
							"-part");

					if (firstText.contains("vertebrae")) {
						option1 = firstText.replace("vertebrae", "vertabrae");

					} else {
						option1 = firstText;
					}

					if (secondText.contains("vertebrae")) {
						option2 = secondText.replace("vertebrae", "vertabrae");

					} else {
						option2 = secondText;
					}

					if (thirdText.contains("vertebrae")) {
						option3 = thirdText.replace("vertebrae", "vertabrae");

					} else {
						option3 = thirdText;
					}

					if (fourthText.contains("vertebrae")) {
						option4 = fourthText.replace("vertebrae", "vertabrae");

					} else {
						option4 = fourthText;
					}

					if (firstText.contains("_(HOOFSIDE)")) {
						isHoofContains = true;
						option1 = firstText.replace("_(HOOFSIDE)", "");

					} else {
						option1 = firstText;
					}

					if (secondText.contains("_(HOOFSIDE)")) {
						isHoofContains = true;
						option2 = secondText.replace("_(HOOFSIDE)", "");

					} else {
						option2 = secondText;
					}

					if (thirdText.contains("_(HOOFSIDE)")) {
						isHoofContains = true;
						option3 = thirdText.replace("_(HOOFSIDE)", "");

					} else {
						option3 = thirdText;
					}

					if (fourthText.contains("_(HOOFSIDE)")) {
						isHoofContains = true;
						option4 = fourthText.replace("_(HOOFSIDE)", "");

					} else {
						option4 = fourthText;
					}

					switch (randomValue) {
					case 0:
						firstButton.setText(option1);
						secondButton.setText(option2);
						thirdButton.setText(option3);
						fourthButton.setText(option4);
						break;
					case 1:
						firstButton.setText(option2);
						secondButton.setText(option1);
						thirdButton.setText(option3);
						fourthButton.setText(option4);
						break;
					case 2:
						firstButton.setText(option3);
						secondButton.setText(option2);
						thirdButton.setText(option1);
						fourthButton.setText(option4);

						break;
					case 3:
						firstButton.setText(option4);
						secondButton.setText(option2);
						thirdButton.setText(option3);
						fourthButton.setText(option1);

						break;

					default:
						break;
					}
					if (isInRaw(fileName)) {
						int imId = getResources().getIdentifier(
								Utils.getFileName(fileName), "raw",
								getClass().getPackage().getName());
						imageView.setImageResource(imId);
					} else {
						imageView.setImageURI(Uri.parse(getFilePath(fileName)));
					}
				} else {
					timerView.setVisibility(View.INVISIBLE);
					tView.setVisibility(View.INVISIBLE);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				if (isTimer) {
					while ((currentIndex < (ja.length()-1)) && (!isExit)) {
						Random random = new Random();
						randomValue = random.nextInt(4);
						if (!isPause) {
							publishProgress("");
						}
						Thread.sleep(waitingTime);

					}
				} else {
					while ((currentIndex < (ja.length())) && (!isExit)) {
						if (isNextQuestion) {
							isNextQuestion = false;
							Random random = new Random();
							randomValue = random.nextInt(4);
							if (currentIndex != -1) {
								Thread.sleep(Constants.POST_CLICK_TIME);
							}
							publishProgress("");
							Thread.sleep(Constants.PRE_CLICK_TIME);
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String unused) {

			int percent = (int) ((countCorrectAnswer * 100) / (ja.length()));
			quesTextView.setVisibility(View.GONE);
			imageView.setAlpha(0x55);
			firstButton.setText("Main Menu");
			secondButton.setText("Try again");
			timerView.setText("0.0");
			thirdButton.setBackgroundResource(R.drawable.btn_facebook);
			thirdButton.setText("");
			fourthButton.setBackgroundResource(R.drawable.btn_twitter);
			fourthButton.setText("");
			
			timerView.setVisibility(View.INVISIBLE);
			tView.setVisibility(View.INVISIBLE);
			alertView.setVisibility(View.VISIBLE);
			pauseView.setVisibility(View.INVISIBLE);
			
			firstButton.setEnabled(true);
			secondButton.setEnabled(true);
			thirdButton.setEnabled(true);
			fourthButton.setEnabled(true);
			
			firstButton.setTextColor(Color.WHITE);
			secondButton.setTextColor(Color.WHITE);
			thirdButton.setTextColor(Color.WHITE);
			fourthButton.setTextColor(Color.WHITE);
			
			firstButton.setBackgroundResource(R.drawable.quize_button);
			secondButton.setBackgroundResource(R.drawable.quize_button);
			
			if (percent < 70) {
				isNextLevel = false;
				congratulationView.setText("Sorry :)");
				alertView.setText("You only scored " + score + " points with "
						+ percent + "% accuracy.");
			} else {
				isNextLevel = true;
				secondButton.setText("Next Level");
				congratulationView.setText("Congratulations !");
				alertView.setText("You have scored " + score + " points with "
						+ percent + "% accuracy.");
				int highestScore = Utils.getLevelHighestScore(
						LearningQuizeActivity.this,
						Constants.KEY_LEARNING_SCORE + level);
				if (score > highestScore) {
					Utils.putLevelHighestScore(LearningQuizeActivity.this,
							Constants.KEY_LEARNING_SCORE + level, score);
					Utils.putPrecentage(LearningQuizeActivity.this,
							Constants.KEY_LEARNING_PERCENTAGE + level, percent);

				}
			}
		}
	}

	private String getJsonString(int level) {
		String jsonFileName;
		JSONObject jo;
		try {

			switch (level) {
			case 0:
				jsonFileName = "Level 1-Quiz 1.json";
				break;
			case 1:
				jsonFileName = "Level 2-Quiz 1.json";
				break;
			case 2:
				jsonFileName = "Level 3-Quiz 1.json";
				break;
			case 3:
				jsonFileName = "Level 4-Quiz 1.json";
				break;

			case 4:
				jsonFileName = "Level 5-Quiz 1.json";
				break;
			case 5:
				jsonFileName = "Level Hoof 1-Quiz 1.json";
				break;
			case 6:
				jsonFileName = "Level Hoof 2-Quiz 1.json";
				break;
			case 7:
				jsonFileName = "Level Hoof 3-Quiz 1.json";
				break;
			case 8:
				jsonFileName = "Level Hoof 4-Quiz 1.json";
				break;
			case 9:
				jsonFileName = "Level Tendon 1-Quiz 1.json";
				break;
			case 10:
				jsonFileName = "Level Tendon 2-Quiz 1.json";
				break;
			case 11:
				jsonFileName = "Level Joints 1-Quiz 1.json";
				break;
			case 12:
				jsonFileName = "Level Ligaments 1-Quiz 1.json";
				break;
			case 13:
				jsonFileName = "Level Head Muscle 1-Quiz 1.json";
				break;
			case 14:
				jsonFileName = "Level Head Bone 1-Quiz 1.json";
				break;
			case 15:
				jsonFileName = "Level Teeth 1-Quiz 1.json";
				break;
			case 16:
				jsonFileName = "Level Organs 1-Quiz 1.json";
				break;
			case 17:
				jsonFileName = "Level Organs 2-Quiz 1.json";
				break;
			case 18:
				jsonFileName = "Level Conformation 1-Quiz 1.json";
				break;
			case 19:
				jsonFileName = "Level Conformation 2-Quiz 1.json";
				break;
			case 20:
				jsonFileName = "Level 6-Quiz 1.json";
				break;
			default:
				jsonFileName = "Level 1-Quiz 1.json";
				break;
			}

			jo = new JSONObject(new String(
					Utils.getFileData(this, jsonFileName)));

			try {

				ja = jo.getJSONObject("root").getJSONArray("horse");
				numOfQuestion = ja.length();
				for (int k = 0; k < ja.length(); k++) {
					String fileName = ja.getJSONObject(k).getString("-parent");
					Log.i("DREG", "fileName = " + Utils.getFileName(fileName));
				}

				nrr = new NoRepeatRandom(0, ja.length() - 1);
				for (int i = 0; i < ja.length(); i++) {
					int testValue[] = new int[4];

					testValue[0] = nrr.GetRandom();

					int count = 0;
					NoRepeatRandom n = new NoRepeatRandom(0, ja.length() - 1);
					for (int j = 0; j < ja.length(); j++) {
						int untargetValue = n.GetRandom();
						if (untargetValue != testValue[0] && count <= 2) {
							testValue[++count] = untargetValue;
						}
					}

					positionList.add(testValue);
				}

				for (int k = 0; k < positionList.size(); k++) {
					Log.i("DREG",
							"1st = " + positionList.get(k)[0] + " 2nd ="
									+ positionList.get(k)[1] + " 3rd ="
									+ positionList.get(k)[2] + " 4th ="
									+ positionList.get(k)[3]);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			return jo.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	private String getFilePath(String fileName) {
		boolean isFound = false;
		fileName = fileName + ".png";
		String path = "";

		if (!isFound) {
			File muscleFile[] = Downloader
					.getFileList(Constants.MUSLES_DIRECTORY);
			if (muscleFile != null) {
				for (int i = 0; i < muscleFile.length; i++) {
					if (muscleFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = muscleFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File hoofFile[] = Downloader.getFileList(Constants.HOOFS_DIRECTORY);
			if (hoofFile != null) {
				for (int i = 0; i < hoofFile.length; i++) {
					if (hoofFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = hoofFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File deepFile[] = Downloader
					.getFileList(Constants.DEEP_MUSCLES_DIRECTORY);

			if (deepFile != null) {
				for (int i = 0; i < deepFile.length; i++) {
					if (deepFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = deepFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File headFile[] = Downloader.getFileList(Constants.HEAD_DIRECTORY);

			if (headFile != null) {
				for (int i = 0; i < headFile.length; i++) {
					if (headFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = headFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File organsFile[] = Downloader
					.getFileList(Constants.ORGANS_DIRECTORY);
			if (organsFile != null) {
				for (int i = 0; i < organsFile.length; i++) {
					if (organsFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = organsFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		return path;
	}

	private boolean isInRaw(String fileName) {
		try {
			int imageId = 0;
			imageId = getResources().getIdentifier(Utils.getFileName(fileName),
					"raw", getClass().getPackage().getName());
			if (imageId != 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			isExit = true;
			imageView.setAlpha(0xFF);
			alertView.setVisibility(View.GONE);
			Intent backIntent = new Intent(LearningQuizeActivity.this,
					LearningBeforeActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private String getImageDirectory(int level) {
		String IMAGE_DIRECTORY = "";
		switch (level) {
		case 3:
			IMAGE_DIRECTORY = Constants.MUSLES_DIRECTORY;
			break;

		case 4:
			IMAGE_DIRECTORY = Constants.MUSLES_DIRECTORY;
			break;
		case 5:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 6:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 7:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 8:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 9:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 10:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 11:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 12:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 13:
			IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
			break;
		case 14:
			IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
			break;
		case 15:
			IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
			break;
		case 16:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		case 17:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		case 18:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		case 19:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		}

		return IMAGE_DIRECTORY;
	}

	private void showTimer(long remainingCountTime) {
		// timerView.setText("10.0");
		bonusScore = 0;
		timer = new CountDownTimer(remainingCountTime, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
				String time = "";
				// Log.i("DREG",
				// "Bonus ="
				// + (Math.ceil((double) millisUntilFinished / 1000)));
				bonusScore = (int) (Math
						.ceil((double) millisUntilFinished / 1000));
				remainingTime = millisUntilFinished;
				long second = millisUntilFinished / 1000;
				long tenth = (millisUntilFinished % 1000) / 100;
				time = second + "." + tenth;
				timerView.setText(time);

			}

			@Override
			public void onFinish() {
				timerView.setText(0 + "." + 0);

			}
		}.start();

	}

	private void faceBookSharing(String message) {
		FacebookShareManager fsm = new FacebookShareManager(this, this,
				Constants.FACEBOOK_APP_ID, Constants.FACEBOOK_PERMISSION);
		fsm.shareMessage(message);

	}

	private void shareInTwitter() {
		TwitterShareManager tsm = new TwitterShareManager(
				LearningQuizeActivity.this, this);
		tsm.shareTweet("I have just score " + score + " in Horse 360");
	}

	private void implementQuize() {
		try {
			new AsyncTask<String, String, String>() {
				private JSONArray ja;
				private JSONObject jo;
				private String option1;
				private String option2;
				private String option3;
				private String option4;
				private String firstText;
				private String secondText;
				private String thirdText;
				private String fourthText;

				@Override
				protected void onPreExecute() {
					try {

						jo = new JSONObject(jsonString);
						ja = jo.getJSONObject("root").getJSONArray("horse");
						for (int k = 0; k < ja.length(); k++) {
							String fileName = ja.getJSONObject(k).getString(
									"-parent");
							Log.i("DREG",
									"fileName = " + Utils.getFileName(fileName));
						}

						nrr = new NoRepeatRandom(0, ja.length() - 1);
						for (int i = 0; i < ja.length(); i++) {
							int testValue[] = new int[4];

							testValue[0] = nrr.GetRandom();

							int count = 0;
							NoRepeatRandom n = new NoRepeatRandom(0,
									ja.length() - 1);
							for (int j = 0; j < ja.length(); j++) {
								int untargetValue = n.GetRandom();
								if (untargetValue != testValue[0] && count <= 2) {
									testValue[++count] = untargetValue;
								}
							}

							positionList.add(testValue);
						}

						for (int k = 0; k < positionList.size(); k++) {
							Log.i("DREG", "1st = " + positionList.get(k)[0]
									+ " 2nd =" + positionList.get(k)[1]
									+ " 3rd =" + positionList.get(k)[2]
									+ " 4th =" + positionList.get(k)[3]);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {
					try {
						firstButton.setVisibility(View.VISIBLE);
						secondButton.setVisibility(View.VISIBLE);
						thirdButton.setVisibility(View.VISIBLE);
						fourthButton.setVisibility(View.VISIBLE);
						imageView.setVisibility(View.VISIBLE);
						currentIndex++;
						isClick = true;
						isHoofContains = false;

						Log.i("DREG", "Current Index=" + currentIndex);
						Log.i("DREG", "Random value = " + randomValue);
						firstButton
								.setBackgroundResource(R.drawable.quize_button);
						secondButton
								.setBackgroundResource(R.drawable.quize_button);
						thirdButton
								.setBackgroundResource(R.drawable.quize_button);
						fourthButton
								.setBackgroundResource(R.drawable.quize_button);

						firstButton.setTextColor(Color.WHITE);
						secondButton.setTextColor(Color.WHITE);
						thirdButton.setTextColor(Color.WHITE);
						fourthButton.setTextColor(Color.WHITE);

						firstButton.setEnabled(true);
						secondButton.setEnabled(true);
						thirdButton.setEnabled(true);
						fourthButton.setEnabled(true);
						pauseView.setEnabled(true);

						if (currentIndex < ja.length()) {
							if (isTimer) {
								showTimer(10000);
							}

							quesTextView.setText("Question "
									+ (currentIndex + 1));

							fileName = ja.getJSONObject(
									positionList.get(currentIndex)[0])
									.getString("-part");

							firstText = ja.getJSONObject(
									positionList.get(currentIndex)[0])
									.getString("-part");

							secondText = ja.getJSONObject(
									positionList.get(currentIndex)[1])
									.getString("-part");
							thirdText = ja.getJSONObject(
									positionList.get(currentIndex)[2])
									.getString("-part");
							fourthText = ja.getJSONObject(
									positionList.get(currentIndex)[3])
									.getString("-part");

							if (firstText.contains("vertebrae")) {
								option1 = firstText.replace("vertebrae",
										"vertabrae");

							} else {
								option1 = firstText;
							}

							if (secondText.contains("vertebrae")) {
								option2 = secondText.replace("vertebrae",
										"vertabrae");

							} else {
								option2 = secondText;
							}

							if (thirdText.contains("vertebrae")) {
								option3 = thirdText.replace("vertebrae",
										"vertabrae");

							} else {
								option3 = thirdText;
							}

							if (fourthText.contains("vertebrae")) {
								option4 = fourthText.replace("vertebrae",
										"vertabrae");

							} else {
								option4 = fourthText;
							}

							if (firstText.contains("_(HOOFSIDE)")) {
								isHoofContains = true;
								option1 = firstText.replace("_(HOOFSIDE)", "");

							} else {
								option1 = firstText;
							}

							if (secondText.contains("_(HOOFSIDE)")) {
								isHoofContains = true;
								option2 = secondText.replace("_(HOOFSIDE)", "");

							} else {
								option2 = secondText;
							}

							if (thirdText.contains("_(HOOFSIDE)")) {
								isHoofContains = true;
								option3 = thirdText.replace("_(HOOFSIDE)", "");

							} else {
								option3 = thirdText;
							}

							if (fourthText.contains("_(HOOFSIDE)")) {
								isHoofContains = true;
								option4 = fourthText.replace("_(HOOFSIDE)", "");

							} else {
								option4 = fourthText;
							}

							switch (randomValue) {
							case 0:
								// firstButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[0])
								// .getString("-part"));
								// secondButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[1])
								// .getString("-part"));
								// thirdButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[2])
								// .getString("-part"));
								// fourthButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[3])
								// .getString("-part"));
								firstButton.setText(option1);
								secondButton.setText(option2);
								thirdButton.setText(option3);
								fourthButton.setText(option4);
								break;
							case 1:
								// firstButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[1])
								// .getString("-part"));
								// secondButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[0])
								// .getString("-part"));
								// thirdButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[2])
								// .getString("-part"));
								// fourthButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[3])
								// .getString("-part"));

								firstButton.setText(option2);
								secondButton.setText(option1);
								thirdButton.setText(option3);
								fourthButton.setText(option4);
								break;
							case 2:
								// firstButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[2])
								// .getString("-part"));
								// secondButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[1])
								// .getString("-part"));
								// thirdButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[0])
								// .getString("-part"));
								// fourthButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[3])
								// .getString("-part"));
								firstButton.setText(option3);
								secondButton.setText(option2);
								thirdButton.setText(option1);
								fourthButton.setText(option4);

								break;
							case 3:
								// firstButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[3])
								// .getString("-part"));
								// secondButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[1])
								// .getString("-part"));
								// thirdButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[2])
								// .getString("-part"));
								// fourthButton.setText(ja.getJSONObject(
								// positionList.get(currentIndex)[0])
								// .getString("-part"));
								firstButton.setText(option4);
								secondButton.setText(option2);
								thirdButton.setText(option3);
								fourthButton.setText(option1);

								break;

							default:
								break;
							}

							if (isInRaw(fileName)) {
								int imId = getResources().getIdentifier(
										Utils.getFileName(fileName), "raw",
										getClass().getPackage().getName());
								imageView.setImageResource(imId);
							} else {
								imageView.setImageURI(Uri
										.parse(getFilePath(fileName)));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						while ((currentIndex < ja.length()) && (!isExit)) {
							if (isTimer) {
								Random random = new Random();
								randomValue = random.nextInt(4);
								if (!isPause) {
									publishProgress("");
								}
								Thread.sleep(Constants.WAITING_TIME);

							} else {
								if (isNextQuestion) {
									isNextQuestion = false;
									Random random = new Random();
									randomValue = random.nextInt(4);
									if (currentIndex != -1) {
										Thread.sleep(Constants.POST_CLICK_TIME);
									}
									publishProgress("");
									Thread.sleep(Constants.PRE_CLICK_TIME);
								}
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {

					int percent = (int) ((countCorrectAnswer * 100) / (ja
							.length()));
					quesTextView.setVisibility(View.GONE);
					imageView.setAlpha(0x55);
					firstButton.setText("Main Menu");
					secondButton.setText("Try again");
					timerView.setText("0.0");
					thirdButton.setBackgroundResource(R.drawable.btn_facebook);
					thirdButton.setText("");
					fourthButton.setBackgroundResource(R.drawable.btn_twitter);
					fourthButton.setText("");
					alertView.setVisibility(View.VISIBLE);
					pauseView.setVisibility(View.INVISIBLE);
					firstButton.setEnabled(true);
					secondButton.setEnabled(true);
					thirdButton.setEnabled(true);
					fourthButton.setEnabled(true);
					if (percent < 70) {
						isNextLevel = false;
						congratulationView.setText("Sorry ):");
						alertView.setText("You only scored " + score
								+ " points with " + percent + "% accuracy.");
					} else {
						isNextLevel = true;
						secondButton.setText("Next Level");
						congratulationView.setText("Congratulations !");
						alertView.setText("You have scored " + score
								+ " points with " + percent + "% accuracy.");
						int highestScore = Utils.getLevelHighestScore(
								LearningQuizeActivity.this,
								Constants.KEY_LEARNING_SCORE + level);
						if (score > highestScore) {
							Utils.putLevelHighestScore(
									LearningQuizeActivity.this,
									Constants.KEY_LEARNING_SCORE + level, score);
							Utils.putPrecentage(LearningQuizeActivity.this,
									Constants.KEY_LEARNING_PERCENTAGE + level,
									percent);

						}
					}
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
